import React, { lazy } from "react";
import { useRoutes, useNavigate, Navigate } from "react-router-dom";

import routes, { routeType } from "./routes";
import { Spin } from "antd";
import _ from "lodash";

import Home from "../pages/Home/index";
import About from "../pages/About/index";

export default function Routes() {
  const element = useRoutes(lazyRoutes);
  return element;
}

// 辅助函数，接收原始路由配置，返回懒加载的路由配置
function convertToLazyRoutes(routes: Array<routeType>) {
  const lazyRoutes = routes.map((route: any) => {
    interface lazyRouteType extends routeType {
      element?: any;
    }

    let lazyRoute: lazyRouteType = { ...route };

    if (route?.component) {
      const Lazycomponent = lazy(route?.component);
      lazyRoute = {
        ...route,
        element: (
          <React.Suspense fallback={<Spin></Spin>}>
            <BeforeEach route={route}>
              <Lazycomponent />
            </BeforeEach>
          </React.Suspense>
        ),
      };
    }

    if (route.children) {
      lazyRoute.children = convertToLazyRoutes(route.children);
    }

    // if (route.redirect && location.pathname !== route.redirect) {
    //   location.href = route.redirect;
    //   }

    // 重定向
    if (route?.redirect) {
      lazyRoute.element = <Navigate to={route.redirect} replace />;
    }

    return lazyRoute;
  });
  return lazyRoutes;
}

const lazyRoutes = convertToLazyRoutes(routes);


function BeforeEach(props: { route: routeType; children: any }) {
  if (props?.route?.meta?.title) {
    document.title = props.route.meta.title;
  }

  if (props?.route?.meta?.needLogin) {
    // 看是否登录
    // const navigate = useNavigate();
    // navigate('/login');
  }

  return <div>{props.children}</div>;
}
